package com.csw.android.dev_utils.ex

import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.util.TypedValue
import androidx.annotation.AttrRes
import androidx.core.content.ContextCompat
import com.csw.android.dev_utils.R


/**
 * Context扩展
 */
object ContextEx {

    /**
     * 获取主题颜色
     * @param resId 例如[R.attr.colorPrimary]、[R.attr.colorOnPrimary]
     */
    fun Context.getThemeColor(@AttrRes resId: Int): Int {
        val typedValue = TypedValue()
        theme.resolveAttribute(resId, typedValue, true)
        return typedValue.data
    }

    /**
     * 获取系统drawable
     * @param resId 例如[R.attr.selectableItemBackground]
     */
    fun Context.getSystemDrawable(@AttrRes resId: Int): Drawable {
        val typedValue = TypedValue()
        theme.resolveAttribute(resId, typedValue, true)
        return theme.obtainStyledAttributes(typedValue.resourceId, intArrayOf(resId)).getDrawable(0)
            ?: throw RuntimeException("can not found ${resId}")
    }

    /**
     * 判断当前是否处于夜间模式。
     */
    fun Context.isNightMode(): Boolean {
        val flag = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_YES
        return flag == Configuration.UI_MODE_NIGHT_YES
    }

    /**
     * 判断是否所有权限都授予应用了
     *
     * @param permissions 所有要检查的权限
     */
    fun Context.isAllPermissionGranted(
        vararg permissions: String
    ): Boolean {
        permissions.forEach { permission ->
            if (
                ContextCompat.checkSelfPermission(
                    this,
                    permission
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }
}